import axios from 'axios'
import type { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios'

// 默认配置
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_ADDRESS,
  timeout: 6000,
  headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
})

// 响应前
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const { headers } = config
    const token = localStorage.getItem('token')
    headers.Authorization = `Bearer ${token}`
    return config
  },
  (err: AxiosError) => {
    // 请求错误
    console.log('request err', err)
    return Promise.reject(err)
  },
)

// 响应后
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data, status } = response
    if (status !== 200) {
      window.$message.error('Unexpected response code')
      return console.log('Unexpected response code')
    }

    if (data.code === 401) {
      window.$message.error(data.message)
      return
    }

    if (data.code !== 200) {
      window.$message.error(data.message)
    }

    return data
  },
  (err: AxiosError) => {
    // 响应错误
    window.$message.error(err.message)
    console.log('response err', err)
    return Promise.reject(err)
  },
)

export { instance }
